<?php

namespace app\api\Service;

use app\common\library\Auth;
use app\common\model\Area;
use think\Config;
use think\Db;

class CartService
{
    /**
     * 获取购物车列表
     *
     * 此函数用于获取当前用户购物车中的商品列表它首先获取用户的ID，
     * 然后根据用户ID查询购物车表中的商品信息，并返回查询结果
     *
     * @return array 返回包含购物车商品总数和商品列表的数组
     */
    public static function getList()
    {
        // 实例化Auth类以获取当前用户信息
        $auth = Auth::instance();

        // 获取当前用户ID
        $user_id = $auth->id;

        // 查询用户购物车中的商品信息，包括商品ID、名称、图片、数量和价格
        $list = \app\admin\model\ShopCart::where(['user_id' => $user_id])->field('id,goods_id,goods_name,goods_image,number,price')->select();

        // 返回查询结果，包括商品总数和商品列表
        return ['code' =>1,'msg'=>'查询成功','data'=>['total' =>count($list),'rows'=>$list]];
    }

    /**
     * 添加商品到购物车
     *
     * @param array $data 包含商品ID和数量的数组
     * @return array 包含操作结果的数组
     */
    public static function add($data)
    {
        // 实例化认证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户的ID
        $user_id = $auth->id;
        // 获取要添加到购物车的商品ID
        $goods_id = $data['goods_id'];
        // 获取要添加的数量，如果没有提供则默认为1
        $number = isset($data['number']) ? $data['number'] : 1;

        // 检查数量是否为正整数
        if((floor($number) - $number) != 0) return ['code' =>0,'msg'=>'数量必须是正整数','data'=>''];

        // 查询商品信息，确保商品存在且状态正常
        $goodsInfo = \app\admin\model\ShopGoods::where(['id'=>$goods_id,'status'=>'normal'])->find();
        if (!$goodsInfo) return ['code' =>0,'msg'=>'商品不存在或已下架','data'=>''];

        // 开始数据库事务
        try{
            // 检查购物车中是否已存在该商品
            $cartInfo = \app\admin\model\ShopCart::where(['user_id' => $user_id,'goods_id' => $goods_id])->find();
            if($cartInfo){
                // 如果存在，则增加数量
                $cartInfo->number += $number;
                $res = $cartInfo->save();
            }else{
                // 如果不存在，则准备插入新的购物车项
                $params = [
                    'user_id'      =>  $user_id,
                    'goods_id'      =>  $goods_id,
                    'goods_name'      =>  $goodsInfo['name'],
                    'goods_image'      =>  $goodsInfo['image'],
                    'number'      =>  $number,
                    'price'      =>  $goodsInfo['paid_price'],
                ];

                $res = \app\admin\model\ShopCart::create($params);
            }

            // 提交事务
            Db::commit();
            // 根据操作结果返回相应的消息
            if($res){
                return ['code'=>1,'msg'=>'操作成功','data'=>''];
            }else{
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 如果发生异常，则回滚事务
            Db::rollback();
            // 返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    /**
     * 编辑购物车商品数量
     *
     * @param array $data 包含购物车ID和数量的数据数组
     * @return array 包含操作结果的数组
     */
    public static function edit($data)
    {
        // 实例化认证类
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;
        // 从输入数据中获取购物车ID
        $cart_id = $data['cart_id'];
        // 从输入数据中获取数量，如果未设置则默认为1
        $number = isset($data['number']) ? $data['number'] : 1;

        // 检查数量是否为非零整数
        if(floor($number) != $number || $number == 0) {
            return ['code' =>0,'msg'=>'数量必须是不为0的整数','data'=>''];
        }

        // 查询购物车信息，确保购物车属于当前用户
        $cartInfo = \app\admin\model\ShopCart::where(['id' => $cart_id,'user_id' => $user_id])->find();
        // 如果购物车信息不存在，返回参数错误
        if (!$cartInfo) return ['code' =>0,'msg'=>'参数错误','data'=>''];

        // 开始数据库事务
        Db::startTrans();
        try{
            // 计算更新后的商品数量
            $sum = $number + $cartInfo['number'];

            // 根据更新后的数量决定是删除购物车项还是更新数量
            if($sum <= 0) {
                // 如果更新后的数量不大于0，删除购物车项
                $res = \app\admin\model\ShopCart::where(['id' => $cart_id,'user_id' => $user_id])->delete();
            }else{
                // 如果更新后的数量大于0，更新购物车项的数量
                $res = \app\admin\model\ShopCart::where(['id' => $cart_id,'user_id' => $user_id])->update(['number'=>$sum]);
            }

            // 提交事务
            Db::commit();
            // 根据操作结果返回相应的消息
            if($res){
                return ['code'=>1,'msg'=>'操作成功','data'=>''];
            }else{
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 如果发生异常，回滚事务
            Db::rollback();
            // 返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    /**
     * 删除购物车中的商品
     *
     * 本函数用于删除用户购物车中指定的商品通过接收包含购物车ID的数组来执行删除操作
     * 需要确保操作的用户已通过身份验证，以防止未授权的访问
     *
     * @param array $data 包含需要删除的购物车项ID的数组
     * @return array 返回一个包含操作结果的数组，包括状态码、消息和数据
     */
    public static function delete($data)
    {
        // 实例化身份验证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;
        // 提取要删除的购物车项ID数组
        $cart_ids = $data['cart_ids'];

        // 检查购物车项ID数组是否为空，如果为空则返回错误信息
        if(empty($cart_ids)) return ['code' =>0,'msg'=>'请选择要删除的项','data'=>''];

        // 开始事务处理，以确保数据库操作的完整性
        Db::startTrans();
        try{
            // 执行删除操作，只删除属于当前用户的指定购物车项
            $res = \app\admin\model\ShopCart::where(['id' => ['in',$cart_ids],'user_id'=>$user_id])->delete();

            // 提交事务，如果删除成功
            Db::commit();
            if($res){
                // 返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];
            }else{
                // 如果删除失败，返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 如果发生异常，回滚事务
            Db::rollback();
            // 返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    // 创建订单
    public static function createOrder($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $address_id = $data['address_id'];
        $goods_ids = $data['goods_ids'];
        $goods_number = $data['goods_number'];

        $used_score = $data['used_score'];
        $user_coupon_id = isset($data['user_coupon_id']) ? $data['user_coupon_id'] : 0;

        $amount = $data['amount'];

        if(!$address_id) return ['code'=>0,'msg'=>"请选择收货地址", 'data'=>''];
        if(!$goods_ids) return ['code'=>0,'msg'=>"商品参数错误", 'data'=>''];
        if(!$goods_number) return ['code'=>0,'msg'=>"商品数量错误", 'data'=>''];
        if( (floor($used_score) - $used_score) != 0) return ['code'=>0,'msg'=>"抵用积分必须为正整数", 'data'=>''];
        $goods_ids = explode(",",$goods_ids);
        $goods_number = explode(",",$goods_number);
        $goods_amount = 0;
        for($i=0;$i<count($goods_ids);$i++){
            $goods_id = $goods_ids[$i];
            $number = $goods_number[$i];
            if(!$goods_id || !$number) return ['code'=>0,'msg'=>"商品参数错误", 'data'=>''];
            if( (floor($number) - $number) != 0) return ['code'=>0,'msg'=>"商品数量必须为正整数", 'data'=>''];
            $goodsInfo = \app\admin\model\ShopGoods::where(['id'=>$goods_id])->field('paid_price,stock_id')->find();
            if(!$goodsInfo['paid_price']){return ['code'=>0,'msg'=>"商品不存在", 'data'=>''];}
            $goods_amount += $goodsInfo['paid_price']*$number;
            $stockInfo = \app\admin\model\ShopStock::where(['id'=>$goodsInfo['stock_id']])->field('total_stock')->find();
            if($number >= $stockInfo['total_stock']) return ['code'=>0,'msg'=>"库存不足", 'data'=>''];
        }

        if($goods_amount != $amount) return ['code'=>0,'msg'=>"订单价格错误", 'data'=>''];

        // 优惠劵判断
        if($user_coupon_id){
            $coupon_id = \app\admin\model\CouponUser::where(['id'=>$user_coupon_id,'user_id'=>$user_id,'status'=>1])->value('coupon_id');
            if(!$coupon_id) return ['code'=>0,'msg'=>'优惠劵参数无效','data'=>''];
            $coupon = \app\admin\model\Coupon::where(['id'=>$coupon_id,'expiretime'=>['>',time()],'deletetime'=>null])
                ->find();
            if(!$coupon) return ['code'=>0,'msg'=>'优惠劵不存在','data'=>''];
            if($coupon['type'] == 1){
                if($amount >= $coupon['reduction_amount']) $coupon_money = $coupon['discount_amount'];
            }elseif ($coupon['type'] == 2){
                $coupon_money = $amount;
            }
            if($coupon['type'] == 2 && $used_score) return ['code'=>0,'msg'=>'维修全免卷和积分不可同时使用','data'=>''];
        }else{
            $coupon_money = 0;
        }

        // 抵扣积分判断
        if($used_score){
            $offset_ratio = Config::get("site.offset_ratio");
            $conversion_ratio = Config::get("site.conversion_ratio");
            if($used_score > $auth->score) return ['code'=>0,'msg'=>'用户积分不足','data'=>''];

            $max_score = bcmul(bcmul($amount, ($offset_ratio/100)),$conversion_ratio);
            if($used_score > $max_score) return ['code'=>0,'msg'=>"最多使用{$max_score}积分",'data'=>''];
            $score_money = bcdiv($used_score, $conversion_ratio);
        }else{
            $score_money = 0;
        }
        $payamount = bcsub(bcsub($amount,$score_money),$coupon_money);

        try{
            $order_no = getNewOrderNo(16);
            $params_order = [
                'order_no'      =>  $order_no,
                'user_id'      =>  $user_id,
                'address_id'      =>  $address_id,
                'used_score'      =>  $used_score,
                'user_coupon_id'      =>  $user_coupon_id,
                'coupon_money'      =>  $coupon_money,
                'amount'      =>  $amount,
                'payamount'    => $payamount,
            ];

            $res = \app\admin\model\ShopOrder::create($params_order);

            $params_item = [];
            for($i=0;$i<count($goods_ids);$i++){
                $goods_id = $goods_ids[$i];
                $number = $goods_number[$i];

                $goods = \app\admin\model\ShopGoods::where(['id'=>$goods_id])->find();
                $params_item[] = [
                    'order_id'  =>  $res['id'],
                    'goods_id'  =>  $goods_id,
                    'goods_name'  =>  $goods['name'],
                    'goods_image'  =>  $goods['image'],
                    'goods_number'  =>  $number,
                    'goods_price'  =>  $goods['paid_price'],
                ];

                // 更新销量
                \app\admin\model\ShopGoods::where(['id'=>$goods_id])->setInc('sales', $number);
                
                // 占用库存
                $stock_id = $goods['stock_id'];
                if($stock_id){
                    $stock = \app\admin\model\ShopStock::where(['id'=>$stock_id])->find();
                    $stock->available_stock = $stock->available_stock - $number;
                    $stock->occupied_stock = $number;
                    $stock->save();
                }
            }
            $orderItem = new \app\admin\model\ShopOrderItem;
            $ret = $orderItem->saveAll($params_item);

            Db::commit();
            if($res && $ret){
                // 修改优惠劵状态
                \app\admin\model\CouponUser::where(['id'=>$user_coupon_id,'user_id'=>$user_id])->update
                (['usedtime'=>time(),'updatetime'=>time(),'status'=>2]);
                
                // 扣除积分
                \app\common\model\User::score(0-$used_score,$user_id,'购买商品积分抵扣');

                return ['code'=>1,'msg'=>'操作成功','data'=>['order_id'=>$res['id']]];
            }else{
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

    }
}